/*
	Adobe Systems Incorporated(r) Source Code License Agreement
	Copyright(c) 2007 Adobe Systems Incorporated. All rights reserved.
	
	Please read this Source Code License Agreement carefully before using
	the source code.
	
	Adobe Systems Incorporated grants to you a perpetual, worldwide, non-exclusive, 
	no-charge, royalty-free, irrevocable copyright license, to reproduce,
	prepare derivative works of, publicly display, publicly perform, and
	distribute this source code and such derivative works in source or 
	object code form without any attribution requirements.  
	
	The name "Adobe Systems Incorporated" must not be used to endorse or promote products
	derived from the source code without prior written permission.
	
	You agree to indemnify, hold harmless and defend Adobe Systems Incorporated from and
	against any loss, damage, claims or lawsuits, including attorney's 
	fees that arise or result from your use or distribution of the source 
	code.
	
	THIS SOURCE CODE IS PROVIDED "AS IS" AND "WITH ALL FAULTS", WITHOUT 
	ANY TECHNICAL SUPPORT OR ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING,
	BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
	FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  ALSO, THERE IS NO WARRANTY OF 
	NON-INFRINGEMENT, TITLE OR QUIET ENJOYMENT.  IN NO EVENT SHALL ADOBE
	OR ITS SUPPLIERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
	EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 
	PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
	OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 
	WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 
	OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOURCE CODE, EVEN IF
	ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

package controls.visualizers
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Shape;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	import flash.media.SoundMixer;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flash.utils.ByteArray;	
	import flash.utils.setTimeout;
	import flash.display.DisplayObject;
	import com.adobe.apps.ascension.localization.LocaleResourceFactory;
	
	public class AMSpectrum extends VisualizerBase implements IVisualizer
	{	
		// Stores current sound wave. Reset on each frame.
		private var bytes:ByteArray;
		
		// 256 length array. Each element is a hexadecimal color that is 
		// calculated in createRainbowGradientArray();
		private var colorArr:Array = new Array(256);
		
		private var output: BitmapData;
		private var peaks: BitmapData;		
		private var displace: Matrix;
		private var rect: Rectangle;
		private var gradient: Array;
		private var darken: ColorTransform;
		
		// Final output images. These scale to the visualization window size
		private var bitmapOutput:Bitmap; 
		private var bitmapPeaks:Bitmap;
		
		public function get visualizerName():String
		{
			return LocaleResourceFactory.localeResource.visualizerAMSpectrumName;
		}
		
		public function get authorName():String
		{
			return "Andre Michelle";
		}		
		
		// Constructor. This is currently called upon application initilization, 
		//not when the visualization is first loaded.
		public function AMSpectrum()
		{	

			super();
			
			// Used to store current sound spectrum. Updated for each new frame.
			bytes = new ByteArray();			
			
			// Set direction that visualization will travel. Two pixels up (x) 
			//for each pixel right (-y).
			displace = new Matrix();
			displace.tx = 2;
			displace.ty = -1;
			
			// Used to darken the visualization as it moves.
			darken = new ColorTransform( 1, 1, 1, 1, -2, -2, -2, 0 );
				
			// Stores current output frame
			rect = new Rectangle( 0, 0, 1, 0 );
			
			gradient = createRainbowGradientArray();
			
			// Create bitmaps
			output = new BitmapData( 450, 450, true, 0 );
			peaks = new BitmapData( 450, 450, true, 0 );		
			bitmapOutput = new Bitmap(output);
			bitmapPeaks = new Bitmap(peaks);

		}		
		
		// Called on resize or on add	
		protected override function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void
		{		
				if(stage.contains(bitmapOutput)) {
					removeChild(bitmapOutput);
					removeChild(bitmapPeaks);
				}
				
				// Draw a black rectangle to serve as the canvas
				graphics.clear();
				graphics.beginFill( 0 , 1);
				graphics.drawRect( 0, 0, unscaledWidth, unscaledHeight );
				graphics.endFill();
				
				// Resize visualizations if window size changed.
				bitmapOutput.width = unscaledWidth;
				bitmapOutput.height = unscaledHeight;
				bitmapPeaks.width = unscaledWidth;
				bitmapPeaks.height = unscaledHeight;
				
				// Add visualizations back to the stage
				addChild(bitmapOutput);
				addChild(bitmapPeaks);
				
		}	
		
		// Called for each frame
		protected override function draw(): void
		{	
			// Draws the sound spectrum line. Calculated in previous frame.
			peaks.fillRect( peaks.rect, 0 );
			
			// Get current sound spectrum. Store in bytes array.
			SoundMixer.computeSpectrum( bytes, true, 0 );
			
			var value: Number;
			var height: Number;
			
			var smooth: Number;
			
			// For each byte, calculate which height to draw the current frame.
			for( var i: int = 0 ; i < 256 ; i++ )
			{
				value = bytes.readFloat();
				
				// As we move along the spectrum we smooth out the current value by
				// reducing the maximum possible increase/drop in height				
				if( i == 0 )
				{
					smooth = value;				
				} 
				else 
				{ 
					smooth += ( value - smooth ) / 12;	
				}
							
				height = 2 + smooth * 0xf0;
				
				rect.x = 2 + i;
				rect.y = 390 + ( i >> 2 ) - height;
				rect.height = height;
				
				peaks.setPixel32( rect.x, rect.y, 0xffffffff );
				
				// Add the rectangle calculated for the current sound byte to the bitmap
				output.fillRect( rect, colorArr[i] );
			}
			
			// Draw the completed bitmap on the stage,
			output.draw( output, displace, darken, null, null, true );
		}
		
		// Generates an array with 256 colors that cycle between black, red, green, and blue
		private function createRainbowGradientArray(): Array
		{
			var outputColor:Number = 0xff000000;
			var gradient: Array = new Array();

			var shape: Shape = new Shape();
			var bmp: BitmapData = new BitmapData( 256, 1, false, 0 );
			
			var colors: Array = [ 0, 0xff0000, 0xffff00, 0x00ff00, 0x00ffff ];
			var alphas: Array = [ 100, 100, 100, 100, 100 ];
			var ratios: Array = [ 0, 16, 128, 192, 255 ];
			
			var matrix: Matrix = new Matrix();
			
			matrix.createGradientBox( 256, 1, 0, 0, 0 );
			
			shape.graphics.beginGradientFill( 'linear', colors, alphas, ratios, matrix );
			shape.graphics.drawRect( 0, 0, 256, 1 );
			shape.graphics.endFill();
			
			bmp.draw( shape );
			
			for( var i: int = 0 ; i < 256 ; i++ )
			{
				gradient[i] = bmp.getPixel( i, 0 );
				colorArr[i] = outputColor | gradient[i];
			}
			
			return gradient;
		}		
	}
}